package com.zy.stock.controller;

import java.io.StringWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zy.stock.domain.Pager;
import com.zy.stock.domain.Stock;
import com.zy.stock.domain.StockOperationRecord;
import com.zy.stock.domain.StockTranscation;
import com.zy.stock.domain.User;
import com.zy.stock.domain.UserStockRl;
import com.zy.stock.dto.StockTranscationDto;
import com.zy.stock.dto.UserStockRlDto;
import com.zy.stock.quartz.AnalyzeJob;
import com.zy.stock.quartz.CrawlJob;
import com.zy.stock.service.StockService;
import com.zy.stock.service.StockTranscationService;
import com.zy.stock.service.UserService;
import com.zy.stock.service.UserStockRlService;
import com.zy.stock.util.CommonUtils;
import com.zy.stock.util.DateEditor;

@Controller
public class StockTranscationController {
	
	private Logger logger = LoggerFactory.getLogger(StockTranscationController.class);
	
	@Autowired
	private AnalyzeJob job;
	
	@Autowired
    private CrawlJob crawlJob;
	
	@Autowired
	private StockTranscationService stockTranscationService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private StockService stockService;
	
	@Autowired
	private UserStockRlService userStockRlService;
	
	@RequestMapping(value = "stockTranscationManage")
	public ModelAndView toStockTranscationManage(HttpServletRequest request) {	
		ModelAndView mav = new ModelAndView("stockTranscation");
		mav.addObject("menuid",6);
		if(StringUtils.isNotEmpty(request.getParameter("userStockRlId"))){
		  mav.addObject("userStockRlId",request.getParameter("userStockRlId"));
		}
		if(StringUtils.isNotEmpty(request.getParameter("userName"))){
			  mav.addObject("userName",request.getParameter("userName"));
			}
		return mav;
	}
	
	@ResponseBody
	@RequestMapping(value = "getStockTranscationPage")
	public String getStockPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		StringWriter writer = new StringWriter();
		String result = "";
		try {
			Integer draw = Integer.parseInt(request.getParameter("draw"));
			Integer start = Integer.parseInt(request.getParameter("start"));
			Integer length = Integer.parseInt(request.getParameter("length"));
			String stockName = request.getParameter("stockName");
			String stockCode = request.getParameter("stockCode");
			String status = request.getParameter("status");
			String userName = request.getParameter("userName");
			String storeNum = request.getParameter("storeNum");
			String orderColumn = request.getParameter("order[0][column]");
			String columnName = request.getParameter("columns[" + orderColumn + "][data]");
			String orderDir = request.getParameter("order[0][dir]");
			String userStockRlId = request.getParameter("userStockRlId");
			Pager<StockTranscationDto> pager = new Pager<>();
			StockTranscationDto dto = new StockTranscationDto();
			dto.setStockName(stockName);
			dto.setStockCode(stockCode);
			dto.setStatus(status);
			dto.setUserName(userName);
			if(StringUtils.isNotEmpty(userStockRlId)){
			  dto.setUserStockRlId(Integer.parseInt(userStockRlId));
			}
			if(StringUtils.isNotEmpty(storeNum)){
              UserStockRl rl = userStockRlService.findByStoreNum(storeNum);
              dto.setUserStockRlId(rl.getId());
            }
			pager.setT(dto);
			pager.setPagenow(start / length + 1);
			pager.setSize(length);
			pager.setOrderCol(columnName);
			pager.setOrder(orderDir);
			Pager<List<StockTranscation>> stations = stockTranscationService.findByCase(pager);
			map.put("data", stations.getT());
			map.put("recordsTotal", stations.getTotal());
			map.put("recordsFiltered", stations.getTotal());
			map.put("draw", draw);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "getStockTranscationById")
	public String getStockTranscationById(HttpServletRequest request) {
		String result = "";
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
			StockTranscation entity = stockTranscationService.findById(id);
			UserStockRl rl =  userStockRlService.findById(entity.getUserStockRlId());
			//处理日期问题
			entity.setRl(rl);
			map.put("data", entity);
			mapper.writeValue(writer, map);
			JSONObject obj = new JSONObject();
			obj.put("data",entity);
			result = JSONObject.toJSONString(obj);
			logger.info("result");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "addStockTranscation")
	public String addStockTranscation(StockTranscation stockTranscation, HttpServletRequest request) {
		try {
			//处理账户id
			User user = userService.findByName(stockTranscation.getUserName());
			if(user!=null){
				stockTranscation.setUserId(user.getId());
			}
			//处理股票id
			List<Stock> stocks = stockService.findByCode(stockTranscation.getStockCode());
			if(stocks!=null&&stocks.size()>0){
				stockTranscation.setStockId(stocks.get(0).getId());
			}
			stockTranscationService.save(stockTranscation);
		} catch (Exception e) {
			e.printStackTrace();
			return CommonUtils.resultJsonString(-1, "error");
		} finally {
			
		}
		return CommonUtils.resultJsonString(0, "succ");
	}
	
	@ResponseBody
	@RequestMapping(value = "updateStockTranscation")
	public Integer updateStockTranscation(StockTranscation stockTranscation, HttpServletRequest request) {
		try {
			//处理账户id
			User user = userService.findByName(stockTranscation.getUserName());
			if(user!=null){
				stockTranscation.setUserId(user.getId());
			}
			//处理股票id
			List<Stock> stocks = stockService.findByCode(stockTranscation.getStockCode());
			if(stocks!=null&&stocks.size()>0){
				stockTranscation.setStockId(stocks.get(0).getId());
			}
			stockTranscationService.update(stockTranscation);
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			
		}
		return 0;
	}
	
	@ResponseBody
	@RequestMapping(value = "deleteStockTranscationById")
	public Integer deleteStockTranscationById(HttpServletRequest request) {
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			stockTranscationService.deleteById(id);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "ignoreById")
	public Integer ignoreById(HttpServletRequest request) {
		try {
			Integer id = Integer.parseInt(request.getParameter("id"));
			stockTranscationService.ignoreById(id);
			return 0;
		} catch (Exception e) {
			logger.error(e.toString());
			return -1;
		} finally {
			
		}
	}
	
	@ResponseBody
	@RequestMapping(value = "checkStockNo")
	public String checkStockNo(HttpServletRequest request) {
		String result = "";
		try {
			String code = request.getParameter("stockCode");
			Integer userId = Integer.parseInt(request.getParameter("userId"));
			String userName = request.getParameter("userName");
			if(StringUtils.isNotEmpty(userName)){
				User user = userService.findByName(userName);
				if(user!=null){
					userId = user.getId();
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			ObjectMapper mapper = new ObjectMapper();
			StringWriter writer = new StringWriter();
//			List<UserStockRl> entity = userStockRlService.findByCode(code);
			Pager<UserStockRlDto> pager = new Pager<>();
			UserStockRlDto dto = new UserStockRlDto();
			dto.setStockCode(code);
			dto.setUserId(userId);
			pager.setT(dto);
            pager.setPagenow(1);
            pager.setSize(100);
			Pager<List<UserStockRl>> entity = userStockRlService.findByCase(pager);
			List<Stock> stocks = stockService.findByCode(code);
			if(stocks!=null&&stocks.size()>0){
			  map.put("stock", stocks.get(0));
			}
			map.put("data", entity.getT());
			map.put("msg", "succ");
			map.put("code", 0);
			mapper.writeValue(writer, map);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	  @RequestMapping(value="/analyze")
	  @ResponseBody
	  public String analyze(){
	    String result = "";
	    try {
	      Map<String, Object> map = new HashMap<String, Object>();
	      ObjectMapper mapper = new ObjectMapper();
	      StringWriter writer = new StringWriter();  
	      crawlJob.crawl();
	      job.analyze();
	      map.put("msg", "succ");
	      map.put("code", 0);
	      mapper.writeValue(writer, map);
	      result = writer.toString();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return result;
	  }
	
	@InitBinder  
    protected void initBinder(HttpServletRequest request,  
                                  ServletRequestDataBinder binder) throws Exception {  
        //对于需要转换为Date类型的属性，使用DateEditor进行处理  
        binder.registerCustomEditor(Date.class, new DateEditor());  
    }  
}
